package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ruoyi.system.domain.PwsStatus;
import com.ruoyi.system.domain.PwsTable;
import com.ruoyi.system.domain.TankInfo;
import com.ruoyi.system.domain.vo.DeviceVo;
import com.ruoyi.system.domain.vo.TankStatusCardData;
import com.ruoyi.system.domain.vo.TankStatusCountData;
import com.ruoyi.system.mapper.TankInfoMapper;
import com.ruoyi.system.service.PwsStatusService;
import com.ruoyi.system.service.PwsTableService;
import com.ruoyi.system.service.TankInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 缸 服务实现类
 * </p>
 *
 * @author tianfu-li
 * @since 2025-44-27
 */
@Service
public class TankInfoServiceImpl extends ServiceImpl<TankInfoMapper, TankInfo> implements TankInfoService {
    @Autowired
    PwsTableService pwsTableService;
    @Autowired
    PwsStatusService pwsStatusService;
    @Autowired
    TankInfoMapper tankInfoMapper;


    @Override
    public List<TankInfo> getTankInfo()  {
        LambdaQueryWrapper<TankInfo> queryWrapper = new LambdaQueryWrapper<>();
        return this.list(queryWrapper);
    }

    @Override
    public List<TankInfo> getTankInfoByLineNo(Long lineNo) {
        LambdaQueryWrapper<TankInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TankInfo::getLineNo,lineNo);
        return this.list(queryWrapper);
    }

    @Override
    public List<DeviceVo> getNowTankInfo() {
        List<TankInfo> tankInfoList = this.getTankInfo();
       DateTimeFormatter simpleDateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        List<DeviceVo> deviceVos = tankInfoList.parallelStream()
                .map(DeviceVo::tankInfoToDeviceVo)
                .collect(Collectors.toList());
        for (DeviceVo deviceVo : deviceVos) {
            PwsTable pwsTable = pwsTableService.getPwsTableByOrderNo(deviceVo.getProductionNumber());
            if (pwsTable != null) {
                try {
                    deviceVo.setStartTime(pwsTable.getStartTime().format(simpleDateFormat));
                    deviceVo.setOperator(pwsTable.getWorkedBy());
                }catch (Exception e){
                    deviceVo.setStartTime("");
                }

                deviceVo.setMatlDes(pwsTable.getMatlDes());
            }

        }

        return deviceVos;
    }

    @Override
    public TankStatusCountData getTankStatusCountData() {
        TankStatusCountData tankStatusCountData = tankInfoMapper.getTankStatusCount();
        return tankStatusCountData;
    }

    @Override
    public List<TankStatusCardData> getTankStatusCardData() {
        List<TankStatusCardData> tankStatusCardDataList=new ArrayList<>();
        List<TankInfo> tankInfoList = this.getTankInfo();
        for (TankInfo tankInfo : tankInfoList) {
            TankStatusCardData tankStatusCardData = new TankStatusCardData();
            if(tankInfo.getTankState()==1){ //设备异常
                tankStatusCardData.setDeviceName(tankInfo.getTank());
                tankStatusCardData.setColor("#FF0000"); //红色
            }else{
                if(StringUtils.isBlank(tankInfo.getOrderNo())){ //没有订单号
                    tankStatusCardData.setDeviceName(tankInfo.getTank());
                    tankStatusCardData.setColor("#6495ED"); //蓝色
                }else{
                    PwsStatus pwsStatus = pwsStatusService.getPwsStatusByOrderNo(tankInfo.getOrderNo());
                    if(pwsStatus!=null){
                        if(pwsStatus.getPremixStatus()==0){//预混-未生产
                            tankStatusCardData.setOrderNumber(tankInfo.getOrderNo().substring(5,12));
                            tankStatusCardData.setDeviceName(tankInfo.getTank());
                            tankStatusCardData.setProductName(pwsTableService.getPwsTableByOrderNo(tankInfo.getOrderNo()).getMatlDes());
                            tankStatusCardData.setColor("#8CB4F5"); //淡蓝色
                        }else if(pwsStatus.getPremixStatus()==1){//预混 -生产中
                            tankStatusCardData.setProductionTime(pwsStatus.getPremixStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                            tankStatusCardData.setProductName(pwsTableService.getPwsTableByOrderNo(tankInfo.getOrderNo()).getMatlDes());
                            tankStatusCardData.setOrderNumber(tankInfo.getOrderNo().substring(5,12));
                            tankStatusCardData.setDeviceName(tankInfo.getTank());
                            tankStatusCardData.setOperator(pwsStatus.getAftermixUser());
                            tankStatusCardData.setColor("#FFFF00"); //黄色
                        }else if(pwsStatus.getPremixStatus()==2){//预混-生产完成
                                if(pwsStatus.getAftermixStatus()==0){//后混-未生产
                                    tankStatusCardData.setOrderNumber(tankInfo.getOrderNo().substring(5,12));
                                    tankStatusCardData.setDeviceName(tankInfo.getTank());
                                    tankStatusCardData.setProductName(pwsTableService.getPwsTableByOrderNo(tankInfo.getOrderNo()).getMatlDes());
                                    tankStatusCardData.setColor("#FFD700"); //浅橙色
                                } else if (pwsStatus.getAftermixStatus() ==1){//后混-生产中
                                    tankStatusCardData.setProductionTime(pwsStatus.getAftermixStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                                    tankStatusCardData.setProductName(pwsTableService.getPwsTableByOrderNo(tankInfo.getOrderNo()).getMatlDes());
                                    tankStatusCardData.setOrderNumber(tankInfo.getOrderNo().substring(5,12));
                                    tankStatusCardData.setDeviceName(tankInfo.getTank());
                                    tankStatusCardData.setOperator(pwsStatus.getAftermixUser());
                                    tankStatusCardData.setColor("#FF8C00"); //橙色
                                } else if (pwsStatus.getAftermixStatus() ==2){//后混-生产完成
                                    if(tankInfo.getId()==1||tankInfo.getId()==2){//7k,10k
                                        if(pwsStatus.getTransferStatus()==0){ //转缸-未生产
                                            tankStatusCardData.setOrderNumber(tankInfo.getOrderNo().substring(5,12));
                                            tankStatusCardData.setDeviceName(tankInfo.getTank());
                                            tankStatusCardData.setProductName(pwsTableService.getPwsTableByOrderNo(tankInfo.getOrderNo()).getMatlDes());
                                            tankStatusCardData.setColor("#CC6F00"); //浅橙色
                                        }
                                        else if(pwsStatus.getTransferStatus()==1){ //转缸-生产中
                                            tankStatusCardData.setProductionTime(pwsStatus.getTransferStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                                            tankStatusCardData.setOrderNumber(tankInfo.getOrderNo().substring(5,12));
                                            tankStatusCardData.setDeviceName(tankInfo.getTank());
                                            tankStatusCardData.setProductName(pwsTableService.getPwsTableByOrderNo(tankInfo.getOrderNo()).getMatlDes());
                                            tankStatusCardData.setOperator(pwsStatus.getTransferUser());
                                            tankStatusCardData.setColor("#76EEC6"); //浅绿
                                        } else if (pwsStatus.getTransferStatus()==2) {//转缸-生产完成
                                            if(pwsStatus.getPackStatus()==0){//包装-未生产
                                                tankStatusCardData.setOrderNumber(tankInfo.getOrderNo().substring(5,12));
                                                tankStatusCardData.setDeviceName(tankInfo.getTank());
                                                tankStatusCardData.setProductName(pwsTableService.getPwsTableByOrderNo(tankInfo.getOrderNo()).getMatlDes());
                                                tankStatusCardData.setColor("#78DEDE"); //浅绿
                                            } else if (pwsStatus.getPackStatus() ==1){//包装-生产中
                                                tankStatusCardData.setProductionTime(pwsStatus.getPackStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                                                tankStatusCardData.setOrderNumber(tankInfo.getOrderNo().substring(5,12));
                                                tankStatusCardData.setDeviceName(tankInfo.getTank());
                                                tankStatusCardData.setProductName(pwsTableService.getPwsTableByOrderNo(tankInfo.getOrderNo()).getMatlDes());
                                                tankStatusCardData.setColor("#79CDCD"); //浅绿
                                            } else if (pwsStatus.getPackStatus()==2) {//包装-生产完成
                                                tankStatusCardData.setDeviceName(tankInfo.getTank());
                                                tankStatusCardData.setColor("#6495ED");//蓝色
                                            }

                                        }

                                    }else{
                                        if(pwsStatus.getPackStatus()==0){//包装-未生产
                                            tankStatusCardData.setOrderNumber(tankInfo.getOrderNo().substring(5,12));
                                            tankStatusCardData.setDeviceName(tankInfo.getTank());
                                            tankStatusCardData.setProductName(pwsTableService.getPwsTableByOrderNo(tankInfo.getOrderNo()).getMatlDes());
                                            tankStatusCardData.setColor("#78DEDE"); //浅绿
                                        } else if (pwsStatus.getPackStatus() ==1){//包装-生产中
                                            tankStatusCardData.setProductionTime(pwsStatus.getPackStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                                            tankStatusCardData.setOrderNumber(tankInfo.getOrderNo().substring(5,12));
                                            tankStatusCardData.setDeviceName(tankInfo.getTank());
                                            tankStatusCardData.setProductName(pwsTableService.getPwsTableByOrderNo(tankInfo.getOrderNo()).getMatlDes());
                                            tankStatusCardData.setColor("#79CDCD"); //浅绿
                                        } else if (pwsStatus.getPackStatus()==2) {//包装-生产完成
                                            tankStatusCardData.setDeviceName(tankInfo.getTank());
                                            tankStatusCardData.setColor("#6495ED");//蓝色
                                        }
                                    }

                                }


                        }

                    }else{
                        //异常情况pwsStatus中没有单号
                        tankStatusCardData.setDeviceName(tankInfo.getTank());
                        tankStatusCardData.setColor("#6495ED"); //蓝色
                    }
                }
            }
            tankStatusCardDataList.add(tankStatusCardData);
        }
        return tankStatusCardDataList;
    }

    @Override
    public Map<String, Object> getMyChartData() {
        Map<String, Object> result = new LinkedHashMap<>();  // 保持插入顺序
       /* try {*/
            // 1.处理核心图表数据
            List<Map<String, Object>> chartDataList = tankInfoMapper.getMyChartData();
            processChartData(chartDataList);
            result.put("chartDataValue", chartDataList);

            // 2.处理X轴标签
            /*Map<String, Object> xAxisData = tankInfoMapper.getMyChartXAxisLabels();
            validateXAxisData(xAxisData);*/
            result.put("myXAxisLabels", tankInfoMapper.getMyChartXAxisLabels().get("myXAxisLabels").toString().split(","));

        /*} catch (DataAccessException e) {
            log.error("数据库访问异常");
        } catch (Exception e) {
            log.error("未知错误");

        }*/

        return result;
    }

    // 数据处理方法
    private void processChartData(List<Map<String, Object>> dataList) {
        for (Map<String, Object> item : dataList) {
            Object rawData = item.get("data");
            if (rawData == null) {
                item.put("data", Collections.emptyList());
                continue;
            }

            // 处理数值转换
            List<Double> processedData = Arrays.stream(rawData.toString().split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(this::safeParseDouble)  // 安全转换方法
                    .filter(Objects::nonNull)     // 过滤转换失败项
                    .collect(Collectors.toList());

            item.put("data", processedData);
        }
    }

    /**
     * 安全转换数字方法
     * @param str 输入字符串
     * @return 转换后的Double，转换失败返回null
     */
    private Double safeParseDouble(String str) {
        try {
            // 处理千分位数字（如 12,345.67）
            //String cleanNumber = str.replaceAll("[^\\d.]", "");
            return Double.parseDouble(str);
        } catch (NumberFormatException e) {
            // 可在此添加日志记录
            // logger.warn("数值转换失败: {}", str);
            return null;
        }
    }
}
